package com.lixy.convert;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import java.io.*;

/**
 * documents4j 方法word转pdf
 * @author lishuai
 * @date 2021/09/26 23:04
 * @version: 1.0
 */
class Word2Pdf {


    /**
     * @param wordPath 需要被转换的word全路径带文件名
     * @param pdfPath  转换之后pdf的全路径带文件名
     */
    public static void word2pdf(String wordPath, String pdfPath) {
        try {
            InputStream docxInputStream = new FileInputStream(wordPath);
            OutputStream outputStream = new FileOutputStream(pdfPath);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.MS_WORD).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
            converter.shutDown();
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static InputStream word2pdf(InputStream in) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IConverter converter = LocalConverter.builder().build();
            converter.convert(in).as(DocumentType.MS_WORD).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
            converter.shutDown();
            System.out.println("success");
            return new ByteArrayInputStream(outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
